﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Modules.Project;
using PmSoft.Entity;
using ManagementApi.Models;
using ManagementApi.Mvc.ApplicationContexts;

namespace ManagementApi.Mvc.Filters
{
    /// <summary>
    /// 必须选择项目过滤器
    /// </summary>
    public class RequireSelProjectActionFilter : IAsyncActionFilter
    {

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var applicationContext = context.HttpContext.RequestServices.GetRequiredService<ManagementApplicationContext>();

            if (applicationContext.CurrentUser is not IProjectUser projectUser)
            {
                context.Result = new JsonResult(ApiResult.Failure("当前非单项目管理用户"));
                return;
            }

            if (!projectUser.ProjectId.HasValue)
            {
                context.Result = new JsonResult(ApiResult.Failure("请选择项目"));
                return;
            }

            await next();

        }
    }
}
